﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Wintellect.LiveFx;
using Microsoft.LiveFX.ResourceModel;

namespace Wintellect.LiveFx.Cloudboard
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class ManagePermissions : Window
	{
    private Clipboard clipboard;

    public ManagePermissions(Clipboard clipboard)
		{
			this.InitializeComponent();

      this.clipboard = clipboard;

      if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
      {
        this.Members.ItemsSource = this.clipboard.Members;
      }
      else
      {
        this.Members.ItemsSource = new List<MemberRegistration>();
      }

      this.Loaded += new RoutedEventHandler(ManagePermissions_Loaded);
    }

    void ManagePermissions_Loaded(object sender, RoutedEventArgs e)
    {
      System.Net.NetworkCredential liveCredentials = Configuration.Instance.GetLiveCredentials(this.clipboard.LiveID);

      if (liveCredentials == null)
      {
        EtwTrace.Trace(EtwTraceLevel.Information, EtwTraceFlag.Diagnostic, "Displaying login dialog...");
        CloudLogin login = new CloudLogin();
        login.Owner = this;
        if (login.ShowDialog() ?? false)
        {
          EtwTrace.Trace(EtwTraceLevel.Information, EtwTraceFlag.Diagnostic, "Obtained login credentials.");
          liveCredentials = login.LiveID;
        }
        else
        {
          EtwTrace.Trace(EtwTraceLevel.Information, EtwTraceFlag.Diagnostic, "The user closed or canceled login dialog.");
        }
      }

      if (liveCredentials != null)
      {
        EtwTrace.Trace(EtwTraceLevel.Warning, EtwTraceFlag.Diagnostic, "Retrieving contact list...");
        ResourceCollection<ContactResource> contacts = MeshHelper.GetContactList(liveCredentials);
        (this.Resources["Contacts"] as ObjectDataProvider).ObjectInstance = from contact in contacts.Entries select contact.WindowsLiveId;
      }
      else
      {
        EtwTrace.Trace(EtwTraceLevel.Warning, EtwTraceFlag.Diagnostic, "Unable to display permissions management dialog - no credentials.");
      }
    }

    public static IEnumerable<String> GetContacts()
    {
      ResourceCollection<ContactResource> contacts = MeshHelper.GetContactList(null);
      return from contact in contacts.Entries select contact.WindowsLiveId;
    }

    public void save_Click(object sender, RoutedEventArgs e)
    {
      this.clipboard.SynchMembers(this.Members.ItemsSource as IList<MemberRegistration>);
      this.Close();
    }

    private void cancel_Click(object sender, RoutedEventArgs e)
    {
      this.Close();
    }
	}
}